import QuestionEntity from "../entities/QuestionEntity";
import QuestionModel from "../models/QuestionModel";

export default class QuestionDao {

  static async create(question: QuestionEntity) {
    const result = await QuestionModel.create({
      ...question,
      items: JSON.stringify(question.items)
    })

    return result.toJSON()
  }

  static async delete(id: string) {
    const result = await QuestionModel.destroy({
      where: {
        id
      }
    })
    return result > 0 ? true : false
  }

  static async findByPage(offset: number = 0, limit: number = 10, options?: Object) {
    const { rows, count } = await QuestionModel.findAndCountAll({
      where: {
        ...options
      },
      offset,
      limit
    })

    return {
      total: count,
      data: rows
    }
  }

  static async findById(id: string) {
    const result = await QuestionModel.findByPk(id);
    const resultJSON = result?.toJSON()
    if (resultJSON.items.length !== 0) {
      resultJSON.items = JSON.parse(resultJSON.items)
    }

    return resultJSON
  }
}